#coding:utf-8
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
import pickle


batch_size = 64
num_classes = 10
epochs = 40

(x_train, y_train, x_test, y_test) = pickle.load(open('digit_train_test.pkl', 'rb'))
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Dense(256, activation='relu', input_shape=(x_train.shape[1],)))
model.add(Dropout(0.5))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))

model.summary()

model.compile(loss = 'categorical_crossentropy',
              optimizer=keras.optimizers.sgd(lr=0.01, momentum=0.9, decay=0.0001),
              metrics=['accuracy'])
history = model.fit(x_train, y_train,
                    batch_size=batch_size,
                    epochs=epochs,
                    validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss', score[0])
print('Test accuracy', score[1])

# save model
model.save('digit_model.h5')


